package com.buer.train.business.service.impl;

import com.buer.train.business.dao.DeptDao;
import com.buer.train.business.domain.DeptDO;
import com.buer.train.business.domain.MenuDO;
import com.buer.train.business.service.DeptService;
import com.buer.train.common.utils.BuildTree;
import com.buer.train.common.utils.Tree;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
public class DeptServiceImpl implements DeptService {
	@Autowired
	private DeptDao deptDao;
	
	@Override
	public DeptDO get(Integer deptId){
		return deptDao.get(deptId);
	}
	
	@Override
	public List<DeptDO> list(Map<String, Object> map){
		return deptDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return deptDao.count(map);
	}
	
	@Override
	public int save(DeptDO dept){
		return deptDao.save(dept);
	}
	
	@Override
	public int update(DeptDO dept){
		return deptDao.update(dept);
	}
	
	@Override
	public int remove(Integer deptId){
		return deptDao.remove(deptId);
	}
	
	@Override
	public int batchRemove(Integer[] deptIds){
		return deptDao.batchRemove(deptIds);
	}

    @Override
    public PageInfo<DeptDO> getDeptList(Map<String, Object> map) {
        PageHelper.startPage(map); //开始起始页
        List<DeptDO> list = deptDao.getDeptList(map); // 获取数据
        PageInfo<DeptDO> page = new PageInfo<>(list); // 实例化PageInfo
        return page;
    }

    @Override
    public DeptDO getOne(Map<String, Object> map){
        return deptDao.getOne(map);
    }

	@Override
	public Tree<DeptDO> getTree() {
		List<Tree<DeptDO>> trees = new ArrayList<>();
		List<DeptDO> arrayList = deptDao.list(null);
		for (DeptDO deptDO : arrayList) {
			Tree<DeptDO> tree = new Tree<>();
			tree.setId(deptDO.getDeptId()+"");
			tree.setParentId(deptDO.getParentId()+"");
			tree.setText(deptDO.getName());
			trees.add(tree);
		}

		// 默认顶级菜单为０或空，根据数据库实际情况调整
		return BuildTree.build(trees);

	}



	@Override
	public int removeLoop(Integer deptId) {
		//递归删除
		deptDao.remove(deptId);
		doRemoveLoop(deptId);
		return 1;
	}

	@Override
	public Tree<DeptDO> getNodeDeptTree() {
		List<Tree<DeptDO>> trees = new ArrayList<>();
		Map map=new HashMap();
		map.put("type","0");
		List<DeptDO> arrayList = deptDao.list(map);
		for (DeptDO deptDO : arrayList) {
			Tree<DeptDO> tree = new Tree<>();
			tree.setId(deptDO.getDeptId()+"");
			tree.setParentId(deptDO.getParentId()+"");
			tree.setText(deptDO.getName());
			trees.add(tree);
		}

		// 默认顶级菜单为０或空，根据数据库实际情况调整
		return BuildTree.build(trees);
	}

	private void doRemoveLoop(Integer deptId){
		Map map=new HashMap();
		map.put("parentId",deptId);
		List<DeptDO> list = deptDao.list(map);
		for (DeptDO deptDO:list){
			deptDao.remove(deptDO.getDeptId());
			doRemoveLoop(deptDO.getDeptId());
		}
	}

}
